/*
 * Copyright (c) xiake6. All Rights Reserved.
 * @author fenglibin
 * @date  2019-04-16 10:00
 */
package net.xiake6.springcloud.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP白名单.
 *
 * @author fenglibino
 * @date 2019-04-16 10:00
 */
public class IPFilter extends ZuulFilter {

  private static Logger logger = LoggerFactory.getLogger(IPFilter.class);

  @Override
  public String filterType() {
    return "pre";
  }

  @Override
  public int filterOrder() {
    return 0;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() throws ZuulException {
    RequestContext ctx= RequestContext.getCurrentContext();
    HttpServletRequest req=ctx.getRequest();
    String ipAddr=this.getIpAddr(req);
    logger.info("请求IP地址为：[{}]",ipAddr);
    List<String> ips=new ArrayList<String>();
    ips.add("172.0.0.1");
    if(!ips.contains(ipAddr)){
      logger.info("IP地址校验不通过！！！");
      ctx.setResponseStatusCode(401);
      ctx.setSendZuulResponse(false);
      ctx.setResponseBody("IpAddr is forbidden!");
    }
    logger.info("IP校验通过。");
    return null;
  }


  /**
   * 获取Ip地址
   * @param request
   * @return
   */
  public  String getIpAddr(HttpServletRequest request){

    String ip = request.getHeader("X-Forwarded-For");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

}

